import React from "react";
import { getHoursList, getMinutesList, Tab } from "./helpers";
import cls from "./RangeTimePicker.module.scss";

type Props = {
  hours: number;
  minutes: number;
  onChange: (h: number, m: number) => void;
  tab?: string;
  start?: Date;
  end?: Date;
};

const ifSameDay = (d1: Date, d2: Date) => {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
};

export const TimePicker: React.FC<Props> = ({
  hours,
  minutes,
  onChange,
  tab,
  start,
  end,
}) => {
  const hoursList = getHoursList();
  const minutesList = getMinutesList();

  const header = `${hours < 10 ? "0" : ""}${hours}:${
    minutes < 10 ? "0" : ""
  }${minutes}`;

  const sameDay = () => {
    return (start && end && ifSameDay(start, end)) || (start && !end);
  };
  const isButtonDisabled = (h: boolean, n: number) => {
    if (h) return start && start?.getHours() > n;
    return (
      start &&
      end &&
      start.getHours() === end.getHours() &&
      start.getMinutes() >= n
    );
  };

  return (
    <div className={cls.time}>
      <div className={cls.time_head}>{header}</div>
      <div className={cls.time_lists}>
        <ul className={cls.time_list}>
          {hoursList.map((h) => (
            <li key={h}>
              <button
                type="button"
                onClick={() => onChange(h, minutes)}
                data-active={hours === h}
                disabled={
                  sameDay() && tab === Tab.end && isButtonDisabled(true, h)
                }
              >
                {h < 10 && "0"}
                {h}
              </button>
            </li>
          ))}
        </ul>
        <ul className={cls.time_list}>
          {minutesList.map((m) => (
            <li key={m}>
              <button
                type="button"
                onClick={() => onChange(hours, m)}
                data-active={minutes === m}
                disabled={
                  sameDay() && tab === Tab.end && isButtonDisabled(false, m)
                }
              >
                {m < 10 && "0"}
                {m}
              </button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};
